const Koa = require('koa')
const bodyparser = require('koa-bodyparser')

const app = new Koa()
const json = require('koa-json')
const onerror = require('koa-onerror')
const logger = require('koa-logger')
const cors = require('koa-cors2')
const  serve = require("koa-static");

// customize module
const orderRoute = require('./router/order')
const addressRoute = require('./router/address')
const userRoute = require('./router/user')
const newsRoute = require('./router/news')
const messageRoute = require('./router/message')
const attractions = require('./router/attractions')

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
	enableTypes: ['json', 'form', 'text']
}))

app.use(cors())
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(async (ctx, next) => {
	const start = new Date()
	await next()
	const ms = new Date() - start
	console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
	if(ctx.status == '404'){
		ctx.response.redirect('/404.html');
	    //ctx.body = '你需要浏览的页面已经飞往火星了，别访问我的页面！'
	}
})

// routes
app.use(orderRoute.routes(), orderRoute.allowedMethods())
app.use(addressRoute.routes(), addressRoute.allowedMethods())
app.use(userRoute.routes(), userRoute.allowedMethods())
app.use(newsRoute.routes(), newsRoute.allowedMethods())
app.use(messageRoute.routes(), messageRoute.allowedMethods())
app.use(attractions.routes(), attractions.allowedMethods())

// module.exports = app 

app.listen(80, function () {
	console.log('server start');
	console.log('localhost:80');
})